package com.qf.java2106.huangshengrui.hotel.controller.backend;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.qf.java2106.huangshengrui.hotel.common.ResultVO;
import com.qf.java2106.huangshengrui.hotel.constant.MethodConstant;
import com.qf.java2106.huangshengrui.hotel.controller.BaseServlet;
import com.qf.java2106.huangshengrui.hotel.dao.IFoodTypeDao;
import com.qf.java2106.huangshengrui.hotel.factory.BeanFactory;
import com.qf.java2106.huangshengrui.hotel.pojos.Food;
import com.qf.java2106.huangshengrui.hotel.pojos.FoodType;
import com.qf.java2106.huangshengrui.hotel.service.IFoodService;
import com.qf.java2106.huangshengrui.hotel.service.IFoodTypeService;
import com.qf.java2106.huangshengrui.hotel.utils.UploadFileUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.UUID;

/**
 * @author q
 * @version V1.0
 * @date 2021/10/25
 **/
@WebServlet("/food")
@MultipartConfig
public class FoodController extends BaseServlet {

    private IFoodService foodService = (IFoodService) BeanFactory.getBean("foodService");

    private IFoodTypeService foodTypeService = (IFoodTypeService) BeanFactory.getBean("foodTypeService");

    /**
     * 判断用户权限
     * @param request
     * @param response
     * @return true为管理员
     * @throws IOException
     * @throws ServletException
     */
    public boolean checkUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Integer userIsAdmin = (Integer) request.getSession().getAttribute("userIsAdmin");
        if (userIsAdmin == 1){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据key查找菜品
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public String search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean b = checkUser(request, response);
        if (!b){
            return "<script>alert('您不是管理员，无权操作~');alert('请点击右侧退出重新登陆~');</script>";
        }
        String keyword = request.getParameter("keyword");
        ResultVO allType = foodTypeService.findAllType();
        ResultVO vo = foodService.findFoodLikeKey(keyword);
        if (allType.getSuccess()){
            request.getSession().setAttribute("foodTypes",allType.getData());
        } else {
            return (String) allType.getData();
        }
        if (vo.getSuccess()){
            request.setAttribute("foodList",vo.getData());
            request.setAttribute("keyword",keyword);
            return MethodConstant.FORWARD_PREFIX + request.getContextPath()+"/backend/detail/food/food-list.jsp";
        } else {
            return (String) vo.getData();
        }
    }

    /**
     * 新增菜品
     * @param request
     * @param response
     */
    public String save(HttpServletRequest request, HttpServletResponse response) throws IOException, InvocationTargetException, IllegalAccessException, ServletException {
        String foodImage = UploadFileUtils.upload(request);
        if ("0".equals(foodImage)){
            return "<script>location.href='"+request.getContextPath()+"/backend/detail/food/food-save.jsp';alert('菜品图片不能为空，请上传~');</script>";
        }
        if ("-1".equals(foodImage)){
            return "<script>alert('菜品图片上传失败~');location.href='"+request.getContextPath()+"/backend/detail/food/food-save.jsp';</script>";
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        Food food = new Food();
        BeanUtils.populate(food,parameterMap);
        System.out.println(food);
        food.setFoodImage(foodImage);
        ResultVO vo = foodService.saveFood(food);
        if (vo.getSuccess()){
            return MethodConstant.REDIRECT_PREFIX + request.getContextPath()+"/food?method=search";
        } else {
            return (String) vo.getData();
        }
    }

    /**
     * 修改ui
     * @param request
     * @param response
     */
    public String updateUi(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Integer id = Integer.valueOf(request.getParameter("id"));
        ResultVO vo = foodService.findFoodById(id);
        if (vo.getSuccess()){
            request.setAttribute("food",vo.getData());
            return MethodConstant.FORWARD_PREFIX + "/backend/detail/food/food-update.jsp";
        } else {
            return (String) vo.getData();
        }
    }

    /**
     * 修改提交
     * @param request
     * @param response
     */
    public String update(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        try {
            //如何快速封装前台请求参数到一个Java实体数据
            Map<String, String[]> parameterMap = request.getParameterMap();
            //实体模型
            Food food = new Food();
            //把map中的数据封装到一个实体模型中。有一个要求，map的key必须和Java实体属性名相同
            BeanUtils.populate(food, parameterMap);
            System.out.println(food);
            String foodImage = UploadFileUtils.upload(request);
            if ("0".equals(foodImage)){
                food.setFoodImage(request.getParameter("image"));
            }else if ("-1".equals(foodImage)){
                return "<script>alert('菜品图片上传失败~');location.href='"+request.getContextPath()+"/backend/detail/food/food-save.jsp';</script>";
            } else {
                food.setFoodImage(foodImage);
            }
            ResultVO vo = foodService.updateFood(food);
            if (vo.getSuccess()){
                return MethodConstant.REDIRECT_PREFIX + request.getContextPath() + "/food?method=search";
            } else {
                return (String) vo.getData();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }

    }

    /**
     * 删除菜品
     * @param request
     * @param response
     */
    public String delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer id = Integer.valueOf(request.getParameter("id"));
        ResultVO vo = foodService.deleteFood(id);
        if (vo.getSuccess()){
            //response.sendRedirect(request.getContextPath()+"/foodtype?method=search");
            return MethodConstant.REDIRECT_PREFIX + request.getContextPath()+"/food?method=search";
        } else {
            //response.getWriter().write((String) vo.getData());
            return (String) vo.getData();
        }
    }

    /**
     * 检查菜名是否存在
     * @param request
     * @param response
     */
    public String nameExists(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String foodName = request.getParameter("foodName");
        ResultVO vo = foodService.findFoodByName(foodName);
        //response.getWriter().write(JSON.toJSONString(vo));
        return JSON.toJSONString(vo);
    }

    /**
     * 上传图片
     * @param request
     * @param response
     */
    public String uploadImg(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //System.out.println("进来了..");

        ServletInputStream in = request.getInputStream();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        String path = request.getServletContext().getRealPath("/images/");

        File file = new File(path, "1.jpg");
        FileOutputStream out = new FileOutputStream(file);

        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len=in.read(buffer))!=-1){
            out.write(buffer, 0, len);
            out.flush();
        }
        out.close();
        in.close();

/*

        Part part = request.getPart("imageUrl");
        String filename = part.getSubmittedFileName();
        if(StringUtils.isEmpty(filename)) {
            return "0";
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String extName = filename.substring(filename.lastIndexOf("."));   //.jpg

        String destName = uuid + extName;  //上传的文件名称

        String path = request.getServletContext().getRealPath("/images/");

        File file = new File(path, destName);

        if(!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
*/

        //part.write(file.getPath());
        //上传的图片应该保存下来     /images/huiguorou.jpg
        return "/images/1.jpg";
    }

}
